package com.pic.others.helper;

import com.pic.common.constants.RedisConstants;
import com.pic.common.utils.UserContext;
import com.pic.others.domain.po.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SaveSearchRecord {
    private static final int max=10;
    @Autowired
    public StringRedisTemplate redisTemplate;

    //保存历史记录
    public  void saveSearchRecord(String info ){
        long userid= UserContext.getUser();
        String redisKey= RedisConstants.jwt.RECENT_HISTORY+"."+userid;//key
        ZSetOperations<String,String>zSetOperations=redisTemplate.opsForZSet();
        zSetOperations.add(redisKey,info,System.currentTimeMillis());
        Long size=zSetOperations.size(redisKey);
        if(size>max){
            zSetOperations.remove(redisKey,0,size-max-1);
        }
        //设置缓存时间一个月
        redisTemplate.expire(redisKey,30, TimeUnit.DAYS);
    }


    //取出来历史记录
    public List<String> getRecentSearchList(){
        List<String>list=new ArrayList<>();
        Long userId = UserContext.getUser();
        String redisKey=RedisConstants.jwt.RECENT_HISTORY+"."+userId;
        ZSetOperations<String,String>zSetOperations=redisTemplate.opsForZSet();
        //取出10
        Set<ZSetOperations.TypedTuple<String>> range = zSetOperations.reverseRangeWithScores(redisKey, 0, max-1);
        for(ZSetOperations.TypedTuple<String>tuple:range){
            list.add(tuple.getValue());
        }
        return list;
    }
    // 删除特定历史记录
    public void deleteSearchRecord(String info) {
        try {
            Long userId = UserContext.getUser();
            String redisKey = RedisConstants.jwt.RECENT_HISTORY + "." + userId;
            ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
            zSetOperations.remove(redisKey, info);
        } catch (Exception e) {
            log.error("Error deleting search record", e);
            // 处理异常，根据需要进行日志记录或其他操作
        }
    }

}
